//=============================================================================
// System  : MatchKit
// File    : RepeaterPattern.cs
// Author  : Fabio Bussu  (matchkit@fabiobussu.it)
// Updated : 04/16/2013
// Note    : Copyright 2013, Fabio Bussu, All rights reserved
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code.  It can also be found
// at the project website: http://matchkit.codeplex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version     Date     Who  Comments
// ============================================================================
// 1.0.0.0  04/16/2013   FB  First draft
//=============================================================================
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MatchKit.Patterns
{
	/// <summary>
	/// Provides the logic to match repeatedly a child pattern, optionally specifying a separator pattern.
	/// </summary>
	/// <threadsafety static="true" instance="false" />
	/// <serialization binary="true" contract="true" />
	/// <conceptualLink target="cb715773-b793-4cc4-acc4-6688cdb22db6" />
	/// <conceptualLink target="0a06b2a9-5f58-409a-ba62-639cfd77bca7" />
	#if DC
	[DataContract]
	#endif
	#if SZ
	[Serializable]
	#endif
	public sealed class RepeaterPattern : BasePattern
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.Patterns.RepeaterPattern"/> class. 
		/// </summary>
		/// <param name="repeatableItem">The repeatable pattern. See <see cref="P:MatchKit.Patterns.RepeaterPattern.RepeatableItem"/>.</param>
		public RepeaterPattern(IPattern repeatableItem)
			: this(repeatableItem, null)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:RepeaterPattern"/> class. 
		/// </summary>
		/// <param name="repeatableItem">The repeatable pattern. See <see cref="P:MatchKit.Patterns.RepeaterPattern.RepeatableItem"/>.</param>
		/// <param name="separatorItem">The separator item. See <see cref="P:MatchKit.Patterns.RepeaterPattern.SeparatorItem"/>.</param>
		public RepeaterPattern(IPattern repeatableItem, IPattern separatorItem)
		{
			RepeatableItem = repeatableItem;
			SeparatorItem = separatorItem;
		}

		/// <inheritdoc />
		public override IEnumerable<IPattern> Children
		{
			get { yield return _repeatableItem; }
		}

		/// <inheritdoc />
		public override bool HasChildren
		{
			get { return true; }
		}

		private IPattern _repeatableItem;
		/// <summary>
		/// Gets or sets the repeatable pattern. This value cannot be null.
		/// </summary>
		/// <serialization member="true" />
		#if DC
		[DataMember]
		#endif
		public IPattern RepeatableItem
		{
			get { return _repeatableItem; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value", "RepeatableItem cannot be null");
				_repeatableItem = value;
			}
		}

		private IPattern _separatorItem;
		/// <summary>
		/// Gets or sets the pattern, if not null, to match after the <see cref="P:MatchKit.Patterns.RepeaterPattern.RepeatableItem"/>. 
		/// If a separator is specified and is not found, the match will success until the last <see cref="P:MatchKit.Patterns.RepeaterPattern.RepeatableItem"/> 
		/// found.
		/// </summary>
		/// <serialization member="true" />
		#if DC
		[DataMember]
		#endif
		public IPattern SeparatorItem
		{
			get { return _separatorItem; }
			set { _separatorItem = value; }
		}

		/// <inheritdoc />
		protected override Match OnMatch(MatchContext context)
		{
			var items = new List<Match>();
			var values = new List<object>();
			#region tracer
			var tracer = context.Tracer;
			int repeatNo = 0;
			#endregion

			while (!context.IsEos)
			{
				#region tracer
				if (tracer != null)
				{
					IMatchTracerExtensions.BeginMatch(tracer, context, _repeatableItem, "Repeat #{0}", ++repeatNo);
				}
				#endregion

				var branch = context.Branch();
				var m = _repeatableItem.Match(branch);

				#region tracer
				if (tracer != null)
				{
					IMatchTracerExtensions.MatchComplete(tracer, context, m, "End repeat #{0}", repeatNo);
				}
				#endregion

				if (!m.Success)
				{
					// se ho fatto match di almeno un elemento considero successo
					if (values.Count != 0)
						break;

					return m;
				}

				context.Commit(branch);
				items.Add(m);
				values.Add(m.Value);

				// REPEATER
				if (_separatorItem != null)
				{
					#region tracer
					if (tracer != null)
					{
						IMatchTracerExtensions.BeginMatch(tracer, context, _separatorItem, "Begin repeater item #{0}", repeatNo);
					}
					#endregion

					branch = context.Branch();
					m = _separatorItem.Match(branch);

					#region tracer
					if (tracer != null)
					{
						IMatchTracerExtensions.MatchComplete(tracer, context, m, "End repeater item #{0}", repeatNo);
					}
					#endregion

					if (!m.Success)
						break;

					context.Commit(branch);
					items.Add(m);
				}
			}

			return Success(context, values.Count != 0 ? values.ToArray() : null, items.ToArray());
		}

		/// <inheritdoc />
		public override string HelpString
		{
			get { return "Repeatable " + _repeatableItem.HelpString; }
		}
	}
}
